package com.app.framework.socket.sender;

import java.util.List;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;

import com.app.framework.socket.Packet;
import com.app.framework.socket.manager.SenderManager;

public abstract class AbstractSender<T> implements Sender<T> {

	private final Logger logger = Logger.getLogger(getClass());
	private Channel channel;
	
	private T id;
	
	private SenderManager<T,? extends Sender<T>> manager;
	
	public AbstractSender(Channel channel,SenderManager<T,? extends Sender<T>> manager) {
		this.channel = channel;
		this.manager = manager;
	}
	
	@Override
	public T getId() {
		return id;
	}
	
	@Override
	public void setId(T t) {
		this.id = t;
	}
	
	@Override
	public boolean isChannelActive() {
		
		return channel != null && channel.isOpen();
	}

	@Override
	public Channel getChannel() {
		return channel;
	}
	
	@Override
	public SenderManager<T,? extends Sender<T>> getManager() {
		return manager;
	}
	@Override
	public ChannelFuture sendMessage(List<Packet> packet) {
		ChannelFuture cf = null;
		if(isChannelActive()) {
			if(channel.isWritable()) {
				cf = channel.write(packet);
			}
			else {
				logger.warn("server2client socket buffer full and discard packet senderId:"+id);
			}
		}
		return cf;
	}
	
	@Override
	public ChannelFuture sendMessage(Packet... packet) {
		ChannelFuture cf = null;
		if(isChannelActive()) {
			if(channel.isWritable()) {
				cf = channel.write(packet);
			}
			else {
				logger.warn("server2client socket buffer full and discard packet senderId:"+id);
			}
		}
		return cf;
	}
	
	@Override
	public void disconnect() {
		if(this.getChannel().isOpen()) {
			this.getChannel().close();
		}
		getManager().removeSender(this);
		close();
	}
	
	protected void close() {
		channel = null;
		manager = null;
	}
}
